<?php
class CustomControllerAclManager extends Zend_Controller_Plugin_Abstract {
	private $_defaultRole = 'guest';
	private $_authController = array('controller' => 'account',
	                                 'action' => 'login');
	
	public function __construct(Zend_Auth $auth){
		$this->auth = $auth;
		$this->acl = new Zend_Acl();
		
		$this->acl->addRole(new Zend_Acl_Role($this->_defaultRole));
		$this->acl->addRole(new Zend_Acl_Role('member'), 'guest');
		$this->acl->addRole(new Zend_Acl_Role('administrator'), 'member');
		
		$this->acl->add(new Zend_Acl_Resource('account'));
		$this->acl->add(new Zend_Acl_Resource('admin'));
		$this->acl->add(new Zend_Acl_Resource('articlemanager'));
		$this->acl->add(new Zend_Acl_Resource('article'));
		$this->acl->add(new Zend_Acl_Resource('albummanager'));
		
		$this->acl->allow();
		$this->acl->deny(null, 'account');
		$this->acl->deny(null, 'admin');
		$this->acl->deny(null, 'article');
		$this->acl->deny(null, 'articlemanager');
		$this->acl->deny(null, 'albummanager');
		
		$this->acl->allow('guest', 'account', array('register',
		                                            'registercomplete',
		                                            'login',
                                                    'fetchpassword'));
		$this->acl->allow('member', 'account', array('detail',
													 'detailcomplete',
													 'logout',
		                                             'index'));
		$this->acl->allow('guest', 'article', array('index',
		                                            'view',
		                                            'articlenotfound'));
		
		$this->acl->allow('member', 'articlemanager', array('edit',
		                                                    'preview',
		                                                    'setstatus',
		                                                    'index'));
		
		$this->acl->allow('member', 'albummanager', array('index',
		                                                  'upload',
		                                                  'create',
		                                                  'preview',
		                                                  'set'));
		$this->acl->allow('administrator', 'admin');
	}
	
	public function preDispatch(Zend_Controller_Request_Abstract $request) {
	
		if ($this->auth->hasIdentity()) {
			$role = $this->auth->getIdentity()->usertype;
			
		} else {
			$role = $this->_defaultRole;
		}
		if (!$this->acl->hasRole($role)) {
			$role = $this->_defaultRole;
		}
		
		$resource = $request->controller;
		$privilege = $request->action;
		if (!$this->acl->has($resource)) {
			$resource = null;
		}
		if (!$this->acl->isAllowed($role, $resource, $privilege)) {
			$request->setControllerName($this->_authController['controller']);
			$request->setActionName($this->_authController['action']);
		}
		
	}
}
?>